home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Gigarom 1
/
Gigarom Macintosh Archives (Quantum Leap)(CDRM1080320)(1993).iso
/
FILES
/
DEV
/
A-B
/
001. Sample.cpt
/
Sample.c
< prev
next >
Wrap
C/C++ Source or Header
|
1988-08-02
|
26KB
|
764 lines
/*------------------------------------------------------------------------------
#
# Apple Macintosh Developer Technical Support
#
# MultiFinder-Aware Simple Sample Application
#
# Sample
#
# Sample.c - C Source
#
# Copyright © 1988 Apple Computer, Inc.
# All rights reserved.
#
# Versions: 1.0 8/88
#
# Components: Sample.p August 1, 1988
# Sample.c August 1, 1988
# Sample.r August 1, 1988
# Sample.h August 1, 1988
# PSample.make August 1, 1988
# CSample.make August 1, 1988
#
# Sample is an example application that demonstrates how to
# initialize the commonly used toolbox managers, operate
# successfully under MultiFinder, handle desk accessories,
# and create, grow, and zoom windows.
#
# It does not by any means demonstrate all the techniques
# you need for a large application. In particular, Sample
# does not cover exception handling, multiple windows/documents,
# sophisticated memory management, printing, or undo. All of
# these are vital parts of a normal full-sized application.
#
# This application is an example of the form of a Macintosh
# application; it is NOT a template. It is NOT intended to be
# used as a foundation for the next world-class, best-selling,
# 600K application. A stick figure drawing of the human body may
# be a good example of the form for a painting, but that does not
# mean it should be used as the basis for the next Mona Lisa.
#
# We recommend that you review this program or TESample before
# beginning a new application.
#
------------------------------------------------------------------------------*/
/* Segmentation strategy:
This program consists of three segments. Main contains most of the code,
including the MPW libraries, and the main program. Initialize contains
code that is only used once, during startup, and can be unloaded after the
program starts. %A5Init is automatically created by the Linker to initialize
globals for the MPW libraries and is unloaded right away. */
/* SetPort strategy:
Toolbox routines do not change the current port. In spite of this, in this
program we use a strategy of calling SetPort whenever we want to draw or
make calls which depend on the current port. This makes us less vulnerable
to bugs in other software which might alter the current port (such as the
bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
Hopefully, this also makes the routines from this program more self-contained,
since they don't depend on the current port setting. */
#include <Values.h>
#include <Types.h>
#include <Resources.h>
#include <QuickDraw.h>
#include <Fonts.h>
#include <Events.h>
#include <Windows.h>
#include <Menus.h>
#include <TextEdit.h>
#include <Dialogs.h>
#include <Desk.h>
#include <ToolUtils.h>
#include <Memory.h>
#include <SegLoad.h>
#include <Files.h>
#include <OSUtils.h>
#include <Traps.h> /* MPW 2.0.2 Traps.h is missing an #endif */
#include <Sample.h> /* bring in all the #defines for Sample */
/* The "g" prefix is used to emphasize that a variable is global. */
/* GMac is used to hold the result of a SysEnvirons call. This makes
it convenient for any routine to check the environment. */
SysEnvRec gMac; /* set up by Initialize */
/* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
trap is available. If it is false, we know that we must call GetNextEvent. */
Boolean gHasWaitNextEvent; /* set up by Initialize */
/* GInBackground is maintained by our osEvent handling routines. Any part of
the program can check it to find out if it is currently in the background. */
Boolean gInBackground; /* maintained by Initialize and DoEvent */
/* The following globals are the state of the window. If we supported more than
one window, they would be attatched to each document, rather than globals. */
/* GStopped tells whether the stop light is currently on stop or go. */
Boolean gStopped; /* maintained by Initialize and SetLight */
/* GStopRect and gGoRect are the rectangles of the two stop lights in the window. */
Rect gStopRect; /* set up by Initialize */
Rect gGoRect; /* set up by Initialize */
/* Here are declarations for all of the C routines. In MPW 3.0 we can use
actual prototypes for parameter type checking. */
#ifndef MPW3
void EventLoop();
void DoEvent( /* EventRecord *event */ );
void AdjustCursor( /* Point mouse, RgnHandle region */ );
void DoUpdate( /* WindowPtr window */ );
void DoActivate( /* WindowPtr window, Boolean becomingActive */ );
void DoContentClick( /* WindowPtr window */ );
void DrawWindow( /* WindowPtr window */ );
void AdjustMenus();
void DoMenuCommand( /* long menuResult */ );
void SetLight( /* WindowPtr window, Boolean newStopped */ );
void DoCloseWindow( /* WindowPtr window */ );
void DoCloseBehind( /* WindowPtr window */ );
void Terminate();
void Initialize();
void GoGetRect( /* short rectID, Rect *theRect */ );
void ForceEnvirons();
Boolean IsAppWindow( /* WindowPtr window */ );
Boolean IsDAWindow( /* WindowPtr window */ );
Boolean TrapAvailable( /* short tNumber, TrapType tType */ );
#else
void EventLoop( void );
void DoEvent( EventRecord *event );
void AdjustCursor( Point mouse, RgnHandle region );
void DoUpdate( WindowPtr window );
void DoActivate( WindowPtr window, Boolean becomingActive );
void DoContentClick( WindowPtr window );
void DrawWindow( WindowPtr window );
void AdjustMenus( void );
void DoMenuCommand( long menuResult );
void SetLight( WindowPtr window, Boolean newStopped );
void DoCloseWindow( WindowPtr window );
void DoCloseBehind( WindowPtr window );
void Terminate( void );
void Initialize( void );
void GoGetRect( short rectID, Rect *theRect );
void ForceEnvirons( void );
Boolean IsAppWindow( WindowPtr window );
Boolean IsDAWindow( WindowPtr window );
Boolean TrapAvailable( short tNumber, TrapType tType );
#endif
/* Make the 2.0 Interface for passing Points to the Toolbox by address,
emulate the 3.0 method of passing Points by value. This list only contains
the affected routines actually used in this sample, and is not intended to
be a comprehensive list of the affected routines.
For routines that have Str255 formal parameters we cannot do a similar trick
so the necessary changes are in the code itself. Searching for MPW3 will find
them. */
#ifndef MPW3
# define FindWindow FINDWINDOW
# define MenuSelect MENUSELECT
# define DragWindow DRAGWINDOW
# define GrowWindow GROWWINDOW
# define TrackBox TRACKBOX
# define PtInRgn PTINRGN
#endif
/* Define HiWrd and LoWrd macros for efficiency. */
#define HiWrd(aLong) (((aLong) >> 16) & 0xFFFF)
#define LoWrd(aLong) ((aLong) & 0xFFFF)
/* Define TopLeft and BotRight macros for convenience. Notice the implicit
dependency on the ordering of fields within a Rect */
#define TopLeft(aRect) (* (Point *) &(aRect).top)
#define BotRight(aRect) (* (Point *) &(aRect).bottom)
extern void _DataInit();
/* This routine is part of the MPW runtime library. This external
reference to it is done so that we can unload its segment, %A5Init. */
#define __SEG__ Main
main()
{
UnloadSeg((Ptr) _DataInit); /* note that _DataInit must not be in Main! */
ForceEnvirons(); /* check for some basic requirements; exits if not met */
MaxApplZone(); /* expand the heap so code segments load at the top */
Initialize(); /* initialize the program */
UnloadSeg((Ptr) Initialize); /* note that Initialize must not be in Main! */
EventLoop(); /* call the main event loop */
}
/* Get events forever, and handle them by calling DoEvent.
Get the events by calling WaitNextEvent, if it's available, otherwise
by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
#define __SEG__ Main
void EventLoop()
{
RgnHandle cursorRgn;
Boolean gotEvent;
EventRecord event;
cursorRgn = NewRgn(); /* we’ll pass WNE an empty region the 1st time thru */
do {
/* use WNE if it is available */
if ( gHasWaitNextEvent )
gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
else {
SystemTask();
gotEvent = GetNextEvent(everyEvent, &event);
}
if ( gotEvent ) {
/* make sure we have the right cursor before handling the event */
AdjustCursor(event.where, cursorRgn);
DoEvent(&event);
}
/* change the cursor (and region) if necessary */
AdjustCursor(event.where, cursorRgn);
} while ( true ); /* loop forever; we quit via ExitToShell */
} /*EventLoop*/
/* Do the right thing for an event. Determine what kind of event it is, and call
the appropriate routines. */
#define __SEG__ Main
void DoEvent(event)
EventRecord *event;
{
short part;
WindowPtr window;
Boolean hit;
char key;
switch ( event->what ) {
case mouseDown:
part = FindWindow(event->where, &window);
switch ( part ) {
case inMenuBar: /* process a mouse menu command (if any) */
AdjustMenus();
DoMenuCommand(MenuSelect(event->where));
break;
case inSysWindow: /* let the system handle the mouseDown */
SystemClick(event, window);
break;
case inContent:
if ( window != FrontWindow() ) {
SelectWindow(window);
/*DoEvent(event);*/ /* use this line for "do first click" */
} else
DoContentClick(window);
break;
case inDrag: /* pass screenBits.bounds to get all gDevices */
DragWindow(window, event->where, &qd.screenBits.bounds);
break;
case inGrow:
break;
case inZoomIn:
case inZoomOut:
hit = TrackBox(window, event->where, part);
if ( hit ) {
SetPort(window); /* the window must be the current port... */
EraseRect(&window->portRect); /* because of a bug in ZoomWindow */
ZoomWindow(window, part, true); /* note that we invalidate and erase... */
InvalRect(&window->portRect); /* to make things look better on-screen */
}
break;
}
break;
case keyDown:
case autoKey: /* check for menukey equivalents */
key = event->message & charCodeMask;
if ( event->modifiers & cmdKey ) /* Command key down */
if ( event->what == keyDown ) {
AdjustMenus(); /* enable/disable/check menu items properly */
DoMenuCommand(MenuKey(key));
}
break;
case activateEvt:
DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
break;
case updateEvt:
DoUpdate((WindowPtr) event->message);
break;
case osEvent:
switch (event->message >> 24) { /* high byte of message */
case suspendResumeMessage: /* suspend/resume is also an activate/deactivate */
gInBackground = (event->message & resumeMask) == 0;
DoActivate(FrontWindow(), !gInBackground);
break;
}
break;
}
} /*DoEvent*/
/* Change the cursor's shape, depending on its position. This also calculates the region
where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
that region, an event would be generated, causing this routine to be called,
allowing us to change the region to the region the mouse is currently in. If
there is more to the event than just “the mouse moved”, we get called before the
event is processed to make sure the cursor is the right one. In any (ahem) event,
this is called again before we fall back into WNE. */
#define __SEG__ Main
void AdjustCursor(mouse,region)
Point mouse;
RgnHandle region;
{
WindowPtr window;
RgnHandle arrowRgn;
RgnHandle plusRgn;
Rect globalPortRect;
window = FrontWindow(); /* we only adjust the cursor when we are in front */
if ( (! gInBackground) && (! IsDAWindow(window)) ) {
/* calculate regions for different cursor shapes */
arrowRgn = NewRgn();
plusRgn = NewRgn();
/* start with a big, big rectangular region */
SetRectRgn(arrowRgn, extremeNeg, extremeNeg, extremePos, extremePos);
/* calculate plusRgn */
if ( IsAppWindow(window) ) {
SetPort(window); /* make a global version of the viewRect */
SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
globalPortRect = window->portRect;
RectRgn(plusRgn, &globalPortRect);
SectRgn(plusRgn, window->visRgn, plusRgn);
SetOrigin(0, 0);
}
/* subtract other regions from arrowRgn */
DiffRgn(arrowRgn, plusRgn, arrowRgn);
/* change the cursor and the region parameter */
if ( PtInRgn(mouse, plusRgn) ) {
SetCursor(*GetCursor(plusCursor));
CopyRgn(plusRgn, region);
} else {
SetCursor(&qd.arrow);
CopyRgn(arrowRgn, region);
}
/* get rid of our local regions */
DisposeRgn(arrowRgn);
DisposeRgn(plusRgn);
}
} /*AdjustCursor*/
/* This is called when an update event is received for a window.
It calls DrawWindow to draw the contents of an application window.
As an effeciency measure that does not have to be followed, it
calls the drawing routine only if the visRgn is non-empty. This
will handle situations where calculations for drawing or drawing
itself is very time-consuming. */
#define __SEG__ Main
void DoUpdate(window)
WindowPtr window;
{
if ( IsAppWindow(window) ) {
BeginUpdate(window); /* this sets up the visRgn */
if ( ! EmptyRgn(window->visRgn) ) /* draw if updating needs to be done */
DrawWindow(window);
EndUpdate(window);
}
} /*DoUpdate*/
/* This is called when a window is activated or deactivated.
In Sample, the Window Manager's handling of activate and
deactivate events is sufficient. Other applications may have
TextEdit records, controls, lists, etc., to activate/deactivate. */
#define __SEG__ Main
void DoActivate(window, becomingActive)
WindowPtr window;
Boolean becomingActive;
{
if ( IsAppWindow(window) ) {
if ( becomingActive )
/* do whatever you need to at activation */ ;
else
/* do whatever you need to at deactivation */ ;
}
} /*DoActivate*/
/* This is called when a mouse-down event occurs in the content of a window.
Other applications might want to call FindControl, TEClick, etc., to
further process the click. */
#define __SEG__ Main
void DoContentClick(window)
WindowPtr window;
{
SetLight(window, ! gStopped);
} /*DoContentClick*/
/* Draw the contents of the application window. We do some drawing in color, using
Classic QuickDraw's color capabilities. This will be black and white on old
machines, but color on color machines. At this point, the window’s visRgn
is set to allow drawing only where it needs to be done. */
#define __SEG__ Main
void DrawWindow(window)
WindowPtr window;
{
SetPort(window);
EraseRect(&window->portRect); /* clear out any garbage that may linger */
if ( gStopped ) /* draw a red (or white) stop light */
ForeColor(redColor);
else
ForeColor(whiteColor);
PaintOval(&gStopRect);
ForeColor(blackColor);
FrameOval(&gStopRect);
if ( ! gStopped ) /* draw a green (or white) go light */
ForeColor(greenColor);
else
ForeColor(whiteColor);
PaintOval(&gGoRect);
ForeColor(blackColor);
FrameOval(&gGoRect);
} /*DrawWindow*/
/* Enable and disable menus based on the current state.
The user can only select enabled menu items. We set up all the menu items
before calling MenuSelect or MenuKey, since these are the only times that
a menu item can be selected. Note that MenuSelect is also the only time
the user will see menu items. This approach to deciding what enable/
disable state a menu item has the advantage of concentrating all
the decision-making in one routine, as opposed to being spread throughout
the application. Other application designs may take a different approach
that is just as valid. */
#define __SEG__ Main
void AdjustMenus()
{
WindowPtr window;
MenuHandle menu;
window = FrontWindow();
menu = GetMHandle(mFile);
if ( IsDAWindow(window) ) /* we can allow desk accessories to be closed from the menu */
EnableItem(menu, iClose);
else
DisableItem(menu, iClose); /* but not our traffic light window */
menu = GetMHandle(mEdit);
if ( IsDAWindow(window) ) { /* a desk accessory might need the edit menu… */
EnableItem(menu, iUndo);
EnableItem(menu, iCut);
EnableItem(menu, iCopy);
EnableItem(menu, iClear);
EnableItem(menu, iPaste);
} else { /* …but we don’t use it */
DisableItem(menu, iUndo);
DisableItem(menu, iCut);
DisableItem(menu, iCopy);
DisableItem(menu, iClear);
DisableItem(menu, iPaste);
}
menu = GetMHandle(mLight);
if ( IsAppWindow(window) ) { /* we know that it must be the traffic light */
EnableItem(menu, iStop);
EnableItem(menu, iGo);
} else {
DisableItem(menu, iStop);
DisableItem(menu, iGo);
}
CheckItem(menu, iStop, gStopped); /* we can also determine check/uncheck state, too */
CheckItem(menu, iGo, ! gStopped);
} /*AdjustMenus*/
/* This is called when an item is chosen from the menu bar (after calling
MenuSelect or MenuKey). It performs the right operation for each command.
It is good to have both the result of MenuSelect and MenuKey go to
one routine like this to keep everything organized. */
#define __SEG__ Main
void DoMenuCommand(menuResult)
long menuResult;
{
short menuID; /* the resource ID of the selected menu */
short menuItem; /* the item number of the selected menu */
short itemHit;
Str255 daName;
short daRefNum;
Boolean handledByDA;
menuID = HiWord(menuResult); /* use macros for efficiency to... */
menuItem = LoWord(menuResult); /* get menu item number and menu number */
switch ( menuID ) {
case mApple:
switch ( menuItem ) {
case iAbout: /* bring up alert for About */
itemHit = Alert(rAboutAlert, nil);
break;
default: /* all non-About items in this menu are DAs */
# ifndef MPW3
/* type Str255 is a struct in MPW 2 */
GETITEM(GetMHandle(mApple), menuItem, &daName);
daRefNum = OPENDESKACC(&daName);
# else
/* type Str255 is an array in MPW 3 */
GetItem(GetMHandle(mApple), menuItem, daName);
daRefNum = OpenDeskAcc(daName);
# endif
break;
}
break;
case mFile:
switch ( menuItem ) {
case iClose:
DoCloseWindow(FrontWindow());
break;
case iQuit:
Terminate();
break;
}
break;
case mEdit: /* call SystemEdit for DA editing & MultiFinder */
handledByDA = SystemEdit(menuItem-1); /* since we don’t do any Editing */
break;
case mLight:
switch ( menuItem ) {
case iStop:
SetLight(FrontWindow(), true);
break;
case iGo:
SetLight(FrontWindow(), false);
break;
}
break;
}
HiliteMenu(0); /* unhighlight what MenuSelect (or MenuKey) hilited */
} /*DoMenuCommand*/
/* Change the setting of the light. */
#define __SEG__ Main
void SetLight( window, newStopped )
WindowPtr window;
Boolean newStopped;
{
if ( newStopped != gStopped ) {
gStopped = newStopped;
SetPort(window);
InvalRect(&window->portRect);
}
} /*SetLight*/
/* Close a window. This handles only desk accessory windows because we do not
allow our window to be closed. TESample provides an example of how to handle
the closing of application windows. */
#define __SEG__ Main
void DoCloseWindow(window)
WindowPtr window;
{
if ( IsDAWindow(window) )
CloseDeskAcc(((WindowPeek) window)->windowKind);
} /*DoCloseWindow*/
/* Close the window that is passed and all windows behind it.
This closes windows from back to front, by calling itself
recursively, which minimizes window updating. Always keep
in mind the dangers of stack overflow when recursive routines
are used in situations where the calling level gets too
deep. That is not a problem here. */
#define __SEG__ Main
void DoCloseBehind(window)
WindowPtr window;
{
if ( window != nil ) { /* if we are passed a window, close other windows behind it first */
DoCloseBehind((WindowPtr) (((WindowPeek) window)->nextWindow));
DoCloseWindow(window); /* now that all the windows behind are closed, close this one */
}
} /*DoCloseBehind*/
/* Clean up the application and exits. We close all of the windows so that
they can update their documents, if any. */
#define __SEG__ Main
void Terminate()
{
DoCloseBehind(FrontWindow()); /* close all windows */
ExitToShell();
} /*Terminate*/
/* Set up the whole world, including global variables, Toolbox managers,
and menus. We also create our one application window at this time.
Since window storage is non-relocateable, how and when to allocate space
for windows is very important so that heap fragmentation does not occur.
Because Sample has only one window and it is only disposed when the application
quits, we will allocate its space here, before anything that might be a locked
relocatable object gets into the heap. This way, we can force the storage to be
in the lowest memory available in the heap. Window storage can differ widely
amongst applications depending on how many windows are created and disposed.
If a failure occurs here, we will assume that the application is in such
bad shape that we should just exit. Your error handling may differ, but
the checks should still be made. */
#define __SEG__ Initialize
void Initialize()
{
Handle menuBar;
WindowPtr window;
gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
gInBackground = false;
InitGraf((Ptr) &qd.thePort);
InitFonts();
InitWindows();
InitMenus();
TEInit();
InitDialogs(nil);
InitCursor();
/* we will allocate our own window storage instead of letting the Window
Manager do it because GetNewWindow may load in temp. resources before
making the NewPtr call, and this can lead to heap fragmentation. */
window = (WindowPtr) NewPtr(sizeof(WindowRecord));
if ( window == nil ) ExitToShell();
window = GetNewWindow(rWindow, (Ptr) window, (WindowPtr) -1);
menuBar = GetNewMBar(rMenuBar); /* read menus into menu bar */
if ( menuBar == nil ) ExitToShell();
SetMenuBar(menuBar); /* install menus */
DisposHandle(menuBar);
AddResMenu(GetMHandle(mApple), 'DRVR'); /* add DA names to Apple menu */
DrawMenuBar();
gStopped = true;
GoGetRect(rStopRect, &gStopRect); /* the stop light rectangle */
GoGetRect(rGoRect, &gGoRect); /* the go light rectangle */
} /*Initialize*/
/* This utility loads the global rectangles that are used by the window
drawing routines. It shows how the resource manager can be used to hold
values in a convenient manner. These values are then easily altered without
having to re-compile the source code. In this particular case, we know
that this routine is being called at initialization time. Therefore,
if a failure occurs here, we will assume that the application is in such
bad shape that we should just exit. Your error handling may differ, but
the check should still be made. */
#define __SEG__ Initialize
void GoGetRect( short rectID, Rect *theRect )
{
Handle resource;
resource = GetResource('RECT', rectID);
if ( resource == nil ) ExitToShell();
*theRect = **((Rect**) resource);
} /* GoGetRect */
/* Make sure that the machine has at least 128K ROMs and enough memory to run.
If it doesn't, exit. SysEnvirons can be called before the toolbox managers
are initialized, and we need to call it at this point so we can check for
the right ROMs and memory availability before we call MaxApplZone and
initialize the toolbox managers. If AppleTalk has not been initialized, you
won't get the version of the AppleTalk driver that is running. That is not
critical here, and if that information was required, SysEnvirons could be
called again after AppleTalk had been initialized. */
#define __SEG__ Main
void ForceEnvirons()
{
OSErr ignoreError;
/* ignore the error returned from SysEnvirons; even if an error occurred,
the SysEnvirons glue will fill in the SysEnvRec */
ignoreError = SysEnvirons(sysEnvironsVersion, &gMac);
if ( (gMac.machineType < 0) ||
(StackSpace() + (long) GetApplLimit() - (long) ApplicZone() < kMinSize * 1024) )
ExitToShell();
/* if you have stack requirements that differ from the default,
then you could use SetApplLimit to increase StackSpace at this point. */
} /* ForceEnvirons */
/* Check to see if a window belongs to the application. If the window pointer
passed was NIL, then it could not be an application window. WindowKinds
that are negative belong to the system and windowKinds less than userKind
are reserved by Apple except for windowKinds equal to dialogKind, which
mean it is a dialog. */
#define __SEG__ Main
Boolean IsAppWindow(window)
WindowPtr window;
{
short windowKind;
if ( window == nil )
return false;
else { /* application windows have windowKinds >= userKind (8) or dialogKind (2) */
windowKind = ((WindowPeek) window)->windowKind;
return (windowKind >= userKind) || (windowKind == dialogKind);
}
} /*IsAppWindow*/
/* Check to see if a window belongs to a desk accessory. */
#define __SEG__ Main
Boolean IsDAWindow(window)
WindowPtr window;
{
if ( window == nil )
return false;
else /* DA windows have negative windowKinds */
return ((WindowPeek) window)->windowKind < 0;
} /*IsDAWindow*/
/* Check to see if a given trap is implemented. This is only used by the
Initialize routine in this program, so we put it in the Initialize segment.
The recommended approach to see if a trap is implemented is to see if
the address of the trap routine is the same as the address of the
Unimplemented trap. */
#define __SEG__ Initialize
Boolean TrapAvailable(tNumber,tType)
short tNumber;
TrapType tType;
{
/* Check and see if the trap exists. On 64K ROM machines, tType will be ignored. */
return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
} /*TrapAvailable*/